//
//  HotDetailViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/29.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "HotDetailViewController.h"
#import "myCell.h"
#import "MJRefresh.h"
#import "AsyncConnection.h"
#import "define.h"
#import "UIImageView+WebCache.h"
#import "ImageSaveViewController.h"
#import "BigImageCollectionViewCell.h"
#import "ImageSaveViewController.h"
#import "ItemDataBase.h"
#import "DataBase.h"
#import "ItemsModel.h"

@interface HotDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *commArr;
@property (nonatomic, retain) NSDictionary *dic;

@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;

@property (nonatomic, retain) ItemsModel *model;


@end

@implementation HotDetailViewController

- (void)dealloc
{
    [_collection release];
    [_array release];
    [_commArr release];
    [_dic release];
    [_model release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.model = [[ItemsModel alloc]init];
        self.array = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
    UIImageView *back = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    back.image = [UIImage imageNamed:@"k16"];
    [self.view addSubview:back];
    [self async];
    self.navigationItem.hidesBackButton = YES;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(20 *_offWidth, 0, 40 *_offWidth, 40 *_offHeight)];
    button.tag = 111;
    [button addTarget:self action:@selector(fanhui:) forControlEvents:UIControlEventTouchUpInside];
    
    for (UIButton *button in self.navigationController.navigationBar.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            button.hidden = YES;
        }
    }
    
    
    [self.navigationController.navigationBar addSubview:button];
    [button setImage:[UIImage imageNamed:@"f.png"] forState:UIControlStateNormal];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    // Do any additional setup after loading the view.
}

- (void)fanhui:(UIButton *)button
{
    

    for (UIButton *button in self.navigationController.navigationBar.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (button.tag == 111) {
                button.hidden = YES;
            }else{
                button.hidden = NO;
            }
        }
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}




- (void)async
{
   
    NSDictionary *dic = @{@"cid":self.pid,
                          @"sid":self.hid,
                          @"info":@"1",
                          @"token":@"1416b90f03d637a168f695105aa4132d7",
                          @"ua":@"iPhone%7C1.7.11",
                          @"lang":@"en",
                          @"sig":@"77fd88165eb31440990879735",
                          @"nt":@"wifi"};
    [AsyncConnection asyncConnection:HOT_DETAIL parmaters:dic block:^(NSData *data) {
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.array = [self.dic objectForKey:@"items"];
        [self createCollectionView];
    }path:[NSString stringWithFormat:@"%@%@", self.pid, self.hid]];
}



#pragma mark -
#pragma mark 整个一个大的tableview

- (void)createCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.itemSize = CGSizeMake(365 *_offWidth, 400 *_offHeight);
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UIImageView *back = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.collection.frame.size.width, self.collection.frame.size.height)];
    [back sd_setImageWithURL:[NSURL URLWithString:[[self.dic objectForKey:@"image"]objectForKey:@"url"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    

    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 69, self.view.frame.size.width, self.view.frame.size.height - 72) collectionViewLayout:flow];
    
    [self.view addSubview:self.collection];
    self.collection.backgroundView = back;
    UIVisualEffectView *visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visual.frame = CGRectMake(0, 0, back.frame.size.width, back.frame.size.height);

    [back addSubview:visual];
    [visual release];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collection registerClass:[BigImageCollectionViewCell class] forCellWithReuseIdentifier:@"image"];
    self.collection.pagingEnabled = YES;
    [self.collection release];
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    scrollView.center = self.collection.center;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.array.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.item == 0) {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor clearColor];
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, 30 *_offHeight, self.view.frame.size.width - 120 *_offWidth, 50 *_offHeight)];
        [cell.contentView addSubview:title];
        title.text = [self.dic objectForKey:@"title"];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, 100 *_offHeight, self.view.frame.size.width - 120 *_offWidth, 260 *_offHeight)];
        title.textColor = [UIColor whiteColor];
        title.numberOfLines = 2;
        [title release];
        UILabel *userName = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, 85 *_offHeight, self.view.frame.size.width - 120 *_offWidth, 20 *_offHeight)];
        [cell.contentView addSubview:userName];
        userName.text = [@"by " stringByAppendingString:[[self.dic objectForKey:@"publisher"]objectForKey:@"name"]];
        userName.textColor = [UIColor whiteColor];
        userName.font = [UIFont systemFontOfSize:15];
        //        label.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.3];
        label.textColor = [UIColor whiteColor];
        NSArray *arr = [UIFont fontNamesForFamilyName:@"Menlo"];
        label.font = [UIFont fontWithName:[arr objectAtIndex:0] size:16];
        [cell.contentView addSubview:label];
        label.text = [self.dic objectForKey:@"desc"];
        label.numberOfLines = 0;
        [label release];
        
        UILabel *visit = [[UILabel alloc]initWithFrame:CGRectMake(40 *_offWidth, cell.contentView.frame.size.height - 40 *_offHeight, 100 *_offWidth, 40 *_offHeight)];
        [cell.contentView addSubview:visit];
        visit.textColor = [UIColor whiteColor];
        visit.text = [[[self.dic objectForKey:@"like"]stringValue] stringByAppendingString:@"人喜欢"];
        visit.font = [UIFont systemFontOfSize:12];
        [visit release];
        return cell;
    }else
    {
        BigImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"image" forIndexPath:indexPath];
        
        cell.contentView.center = CGPointMake(self.view.frame.size.width / 2, 200);
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[[[[self.array objectAtIndex:indexPath.item - 1]objectForKey:@"images"]objectAtIndex:0] objectForKey:@"url"]] placeholderImage:nil];
        
        
        cell.like.tag = indexPath.item - 1;
       BOOL ss = [ItemDataBase selectWithid:[NSString stringWithFormat:@"%ld",(self.hid.integerValue + indexPath.item - 1)]];
        if (ss) {
            [cell.like setImage:[UIImage imageNamed:@"sxin.png"] forState:UIControlStateNormal];
            [cell.like setTintColor:[UIColor cyanColor]];
            cell.like.selected = YES;
        }else
        {
            [cell.like setImage:[UIImage imageNamed:@"cyan.png"] forState:UIControlStateNormal];
            [cell.like setTintColor:[UIColor cyanColor]];
            cell.like.selected = NO;
        }
        [cell.like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(save:)];
        cell.image.userInteractionEnabled = YES;
        [cell.image addGestureRecognizer:tap];
        [tap release];
        
        cell.brand.text = [[[self.array objectAtIndex:indexPath.item - 1]objectForKey:@"brand"]objectForKey:@"brE"];
        
        

    return cell;
    }
}

- (void)save:(UITapGestureRecognizer *)save
{
    ImageSaveViewController *iiii = [[ImageSaveViewController alloc]init];
    iiii.image = ((UIImageView *)save.view).image;
    
    iiii.width = 300 * _offWidth;
    iiii.height = 300 *_offHeight;
    [self.navigationController pushViewController:iiii animated:YES];
}

- (void)like:(UIButton *)button
{
    
        [DataBase dataBaseOpen];
        [self.model setValuesForKeysWithDictionary:[[self.array objectAtIndex:button.tag]objectForKey:@"component"]];
        
        if (button.selected == YES) {
            [DataBase dataBaseOpen];
            [ItemDataBase deleteWithid:self.model.iid];
            [button setTintColor:[UIColor cyanColor]];
            
        }
        if (button.selected == NO) {
            self.model.iid = [NSString stringWithFormat:@"%ld",(self.hid.integerValue + button.tag)];
            self.model.desc = [[[self.array objectAtIndex:button.tag]objectForKey:@"brand"]objectForKey:@"brE"];
            self.model.width = 180 *_offWidth;
            self.model.height = 210 *_offHeight;
            self.model.picUrl = [[[[self.array objectAtIndex:button.tag]objectForKey:@"images"]objectAtIndex:0] objectForKey:@"url"];
            self.model.collectionCount = [[self.dic objectForKey:@"like"]stringValue];
            [button setImage:[UIImage imageNamed:@"sxin.png"] forState:UIControlStateNormal];
            [button setTintColor:[UIColor cyanColor]];
            [ItemDataBase insertWithModel:self.model];

            
        }
        if (button.selected == YES) {
            button.selected = NO;
        }else
        {
            button.selected = YES;
        }
        
    }





//+ (CGFloat)heightWithText:(NSString *)text
//{
//    // 参数1: 预定的矩形大小
//    // 参数2: 图形选项
//    // 参数3: 属性字典(设置字体大小, 一般和cell中的设置成一样的)
//    // 参数4: 内容文本 一般设置为空nil
//    CGRect rect = [text boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
//    return rect.size.height;
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
